package com.rw.coco.data.data;

import com.rw.coco.api.data.CacheMapper;
import com.rw.tool.util.cache.CacheHashMap;
import com.rw.tool.util.io.FileIOUtil;

import java.io.File;
import java.util.Optional;

/**
 * 文件缓存mapper
 */
public class FileCacheMapper implements CacheMapper {
    private static final String CACHE_FILE_NAME = "\\cache\\CacheHashMap.cache";

    private final File CACHE_FILE;

    public FileCacheMapper(String workPath) {
        CACHE_FILE = new File(workPath, CACHE_FILE_NAME);
    }

    @Override
    public synchronized void save(String key, int data, long millisecond) {
        CacheHashMap<String, Integer> cacheMap = getCacheMap();
        cacheMap.put(key, data, millisecond);

        writeFile(cacheMap);
    }

    @Override
    public Optional<Integer> increment(String key) {
        CacheHashMap<String, Integer> cacheMap = getCacheMap();
        Integer count = cacheMap.get(key);
        if (count == null) {
            return Optional.empty();
        }
        cacheMap.replace(key, count + 1);
        writeFile(cacheMap);
        return Optional.of(count + 1);
    }


    @Override
    public Optional<Integer> get(String key) {
        return Optional.ofNullable(getCacheMap().get(key));
    }

    @Override
    public synchronized void delete(String key) {
        CacheHashMap<String, Integer> cacheMap = getCacheMap();
        cacheMap.remove(key);

        writeFile(cacheMap);
    }

    private CacheHashMap<String, Integer> getCacheMap() {
        if (!CACHE_FILE.isFile()) {
            CacheHashMap<String, Integer> cacheHashMap = new CacheHashMap<>();
            FileIOUtil.writeObject(CACHE_FILE, cacheHashMap);
            return cacheHashMap;
        }

        return FileIOUtil.readObject(CACHE_FILE);
    }

    private void writeFile(CacheHashMap<String, Integer> cacheMap) {
        FileIOUtil.writeObject(CACHE_FILE, cacheMap);
    }
}
